package org.ru.mse10.cvis.web.bean.action.login;

import java.util.ResourceBundle;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.ru.mse10.cvis.entity.cv.User;
import org.ru.mse10.cvis.service.EntityService;
import org.ru.mse10.cvis.service.UserService;
import org.ru.mse10.cvis.web.bean.BaseFormBean;

/**
 * The Class UserLoginAction.
 */
@SessionScoped
@ManagedBean(name = "loginAction")
public class UserLoginAction extends BaseFormBean<User, EntityService> {

	/** The user service. */
	@EJB
	private UserService userService;

	/** The context. */
	private final FacesContext context = FacesContext.getCurrentInstance();

	/** The bundle. */
	private final ResourceBundle bundle = context.getApplication()
			.getResourceBundle(context, "message");

	/**
	 * Inits the.
	 * 
	 * @param user
	 *            the user
	 */
	private void init(User user) {
		setTargetEntity(user);
	}

	/**
	 * Inits the login.
	 * 
	 * @return the string
	 */
	public String initLogin() {
		init(new User());
		return "loginPage";
	}

	/**
	 * Login.
	 * 
	 * @return the string
	 */
	public String login() {
		Long userId = userService.checkLogin(getTargetEntity().getEmail(),
				getTargetEntity().getPassword());
		if (userId == null) {
			FacesContext.getCurrentInstance().addMessage(
					"loginForm",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, bundle
							.getString("msgEmail"), null));
			return null; // reload same page
		}
		setLoggedUser(userId);
		setUser(getLoggedUser());
		setTargetEntity(null);
		return "loginSuccessful";
	}

	/**
	 * Logout.
	 * 
	 * @return the string
	 */
	public String logout() {
		setUser(null);
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		session.invalidate();
		return "loginPage";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.ru.mse10.cvis.web.bean.BaseFormBean#getTargetEntity()
	 */
	@Override
	public User getTargetEntity() {
		User user = super.getTargetEntity();
		if (user == null) {
			user = new User();
			setTargetEntity(user);
		}
		return user;
	}
}
